﻿using System;
using TeamTasker.Contracts;
using TeamTasker.Server.BusinessLogic.Staff;
using TeamTasker.Server.DataAccess;

namespace TeamTasker.Server.BusinessLogic
{
    public class SessionFacade : BaseFacade<Session, SessionDAO>
    {
        public StaffRepository StaffRepository { get; set; }
        public UserFacade UserFacade { get; set; }

        private static bool usersSyncDone = false;

        public Session Login(string login, string password) {
            // TODO: timer-based refresh of user list
            if (!usersSyncDone)
            {
                StaffRepository.SynchronizeUserList();
                usersSyncDone = true;
            }

            bool result = StaffRepository.CheckUser(login, password);
            if (result) {
                User user = UserFacade.Load(login);
                Session session = new Session();
                session.UserID = user.ID;
                session.StartTime = DateTime.Now;
                session.LastRequestTime = DateTime.MaxValue;
                Save(session);
                UserFacade.UpdateLoginTimestamp(login);
                return session;
            }
            return null;
        }
        
    }
}
